<template>
  <div class="change-password-box">
    <h1 id="form-title">用户注册</h1>
    <form @submit.prevent="handleRegister">

      <!-- 用户名 -->
      <div class="form-item">
        <label for="username">用户名:</label>
        <input
            type="text"
            id="username"
            v-model="username"
            required
            class="inputStyle"
        />
      </div>

      <!-- 电话号码 -->
      <div class="form-item">
        <label for="phoneNumber">电话号码:</label>
        <input
            type="text"
            id="phoneNumber"
            v-model="phoneNumber"
            required
            class="inputStyle"
        />
      </div>

      <!-- 密码 -->
      <div class="form-item">
        <label for="password">密码:</label>
        <input
            type="password"
            id="password"
            v-model="password"
            required
            class="inputStyle"
        />
      </div>

      <!-- 角色选择 -->
      <div class="form-item">
        <div class="role-selection">
          <div>
            <input type="radio" id="role-user" value="user" v-model="userRole" />
            <label for="role-user">普通用户</label>
          </div>
          <div>
            <input type="radio" id="role-inheritor" value="inheritor" v-model="userRole" />
            <label for="role-inheritor">传承人</label>
          </div>
        </div>
      </div>

      <!-- 真实姓名（仅传承人需要） -->
      <div class="form-item" v-if="userRole === 'inheritor'">
        <label for="realName">真实姓名:</label>
        <input
            type="text"
            id="realName"
            v-model="realName"
            required
            class="inputStyle"
        />
      </div>

      <!-- 非遗类别（仅传承人需要） -->
      <div class="form-item" v-if="userRole === 'inheritor'">
        <label for="heritageCategory">非遗类别:</label>
        <div class="input-container">
          <select
              id="heritageCategory"
              v-model="heritageCategory"
              required
              class="inputStyle"
          >
            <option value="">请选择非遗类别</option>
            <option value="民间文学">民间文学</option>
            <option value="传统音乐">传统音乐</option>
            <option value="传统舞蹈">传统舞蹈</option>
            <option value="传统戏剧">传统戏剧</option>
            <option value="曲艺">曲艺</option>
            <option value="传统体育、游艺与杂技">传统体育、游艺与杂技</option>
            <option value="传统美术">传统美术</option>
            <option value="传统技艺">传统技艺</option>
            <option value="传统医药">传统医药</option>
            <option value="民俗">民俗</option>
          </select>
        </div>
      </div>

      <!-- 注册按钮 -->
      <div class="form-item">
        <button type="submit" class="register-form-button">注册</button>
      </div>

      <!-- 返回登录页面 -->
      <div class="action-links">
        <a @click="handleLogin" class="link-text">已有账号？立即登录</a>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios'; // ✅ 新增这行：引入 axios
import { ElMessageBox } from 'element-plus';
import { registerUser } from '@/api/user.js'

export default {
  data() {
    return {
      username:'',
      phoneNumber: '',
      password: '',
      userRole: 'user',
      realName: '',
      heritageCategory: ''
    };
  },
  computed: {
    isPhoneNumberValid() {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(this.phoneNumber);
    },
    isPasswordValid() {
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
      return passwordRegex.test(this.password);
    }
  },
  methods: {
    async handleRegister() {
      if (!this.username.trim()) {
        await this.showError('请输入用户名');
        return;
      }

      if (!this.isPhoneNumberValid) {
        await this.showError('请输入有效的11位手机号码');
        return;
      }

      if (!this.isPasswordValid) {
        await this.showError('密码必须为8到16位的字母和数字组合');
        return;
      }

      if (this.userRole === 'inheritor' && !this.heritageCategory) {
        await this.showError('请选择非遗类别');
        return;
      }

      this.submitRegistration();
    },

    async showError(message) {
      console.error('弹出错误:', message); // 添加日志
      try {
        await ElMessageBox.alert(message, '提示', {
          confirmButtonText: '确定',
          type: 'error',
          center: true,
          customClass: 'custom-message-box'
        });
      } catch (err) {
        console.error('弹窗异常:', err);
      }
    },

    async submitRegistration() {
      const { username, password, phoneNumber, userRole } = this;

      const roleMapping = {
        user: "4",
        inheritor: "3"
      };

      const userData = {
        username,
        password,
        phone: phoneNumber,
        role: roleMapping[userRole]
      };

      try {
        console.log('用户数据:', userData);
        const response = await registerUser(userData); // ✅ 使用封装好的 registerUser
        console.log('注册成功:', response.data);
        this.$router.push('/home');
      } catch (error) {
        console.error('注册失败:', error);
        await this.showError('注册失败，请重试或联系管理员。');
      }
    },


    handleLogin() {
      this.$router.push('/');
    }
  }
};
</script>

<style scoped>
.change-password-box {
  background: linear-gradient(to bottom right, rgba(13, 13, 13, 0.55) 0%, white 60%, rgba(13, 13, 13, 0.55) 100%);
  width: 380px;
  height: 550px;
  margin: 0 auto;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(8px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

#form-title {
  margin-top: 5px;
  text-align: center;
  font-size: 36px;
  font-weight: bold;
  color: #2c3e50;
}

.form-item {
  margin-bottom: 5px;
  width: 100%;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #34495e;
  font-weight: 500;
}

.inputStyle {
  width: 100%;
  height: 36px;
  padding: 0 15px;
  border: 2px solid #bdc3c7;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.inputStyle:focus {
  border-color: #3498db;
  outline: none;
}

.register-form-button {
  font-size: 16px;
  width: 100%;
  height: 45px;
  background: #28292CFF;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.3s;
  margin-top: 10px;
}

.register-form-button:hover {
  background: #000000FF;
}

.action-links {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  width: 100%;
}

.link-text {
  color: #2c3e50;
  cursor: pointer;
  font-size: 0.95rem;
  text-decoration: underline;
  transition: color 0.3s;
}

.link-text:hover {
  color: #e74c3c;
}

.role-selection {
  display: flex;
  gap: 20px;
}

@media (max-width: 768px) {
  #form-title {
    font-size: 36px;
  }
  .inputStyle {
    height: 38px;
  }
  .register-form-button {
    height: 42px;
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .action-links {
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }
}
</style>
